package com.ayf.payment.game.api.wx;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.ayf.payment.game.api.controller.player.AybSendMsgUtils;
import com.ayf.payment.game.api.dto.PartitionDTO;
import com.ayf.payment.game.api.dto.platform.WxMsgConfigDTO;
import com.ayf.payment.game.api.entity.Merchant;
import com.ayf.payment.game.api.entity.MerchantAccount;
import com.ayf.payment.game.api.entity.Order;
import com.ayf.payment.game.api.entity.platform.WxConfig;
import com.ayf.payment.game.api.entity.platform.WxMsgConfig;
import com.ayf.payment.game.api.entity.platform.WxUser;
import com.ayf.payment.game.api.service.MerchantAccountService;
import com.ayf.payment.game.api.service.MerchantService;
import com.ayf.payment.game.api.service.PartitionService;
import com.ayf.payment.game.api.service.platform.NetConfigService;
import com.ayf.payment.game.api.service.platform.WxConfigService;
import com.ayf.payment.game.api.service.platform.WxMsgConfigService;
import com.ayf.payment.game.api.service.platform.WxUserService;
import com.ayf.payment.game.api.utils.DateUtils;
import com.swwx.charm.commons.lang.utils.LogPortal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * @Description: 发送微信通知信息工具类
 * @Author: zh-liang
 * @Date : 2020-07-07 11:16
 */
@Component
public class WxSendMsgUtils {

    @Autowired
    private WxMsgConfigService wxMsgConfigService;
    @Autowired
    private WxConfigService wxConfigService;
    @Autowired
    private WxUserService wxUserService;
    @Autowired
    private PartitionService partitionService;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private NetConfigService netConfigService;
    @Autowired
    private MyConstant myConstant;
    @Autowired
    private AybSendMsgUtils aybSendMsgUtils;

    @Autowired
    private MerchantAccountService merchantAccountService;


    public void bindWx(String openid, String accountName, Date date, String remark) {
        LogPortal.info("openid【{}】绑定微信成功提醒开始发送，绑定账号【{}】", openid, accountName);
        WxConfig config = wxConfigService.getConfig();
        if (config.getStatus() == 0) {
            LogPortal.info("openid【{}】绑定微信成功提醒发送结束，该微信公众号为关闭状态", openid);
            return;
        }
        WxMsg wxMsg = new WxMsg();
        wxMsg.setOpenid(openid);
//        String tempId = wxMsgConfigService.getTempId(WxMsgType.BIND_WX.getTemplateIdShort());
        // 根据模板code获取模板信息
        WxMsgConfig wxMsgConfig = wxMsgConfigService.getTempIdNew(WxMsgType.BIND_WX.getTemplateIdShort());
        if (wxMsgConfig == null){
            return;
        }
        wxMsg.setTemplateId(wxMsg.getTemplateId());
        wxMsg.setFirst("账号绑定成功");
        wxMsg.setKeyword1(accountName);
        wxMsg.setKeyword2(DateUtils.dateToString(date));
        // 设置key
        wxMsg.setConfig(JSON.parseObject(wxMsgConfig.getConfig()));
        wxMsg.setRemark(remark);
//        myConstant.sendTemplateMsg(config, wxMsg);
        myConstant.sendTemplateMsgNew(config, wxMsg);
        LogPortal.info("openid【{}】绑定微信成功提醒发送完成，绑定账号【{}】", openid, accountName);
    }

    public void unbindWx(String openid, String accountName) {
        LogPortal.info("openid【{}】解绑微信成功提醒开始发送，解绑账号【{}】", openid, accountName);
        WxConfig config = wxConfigService.getConfig();
        if (config.getStatus() == 0) {
            LogPortal.info("openid【{}】解绑微信成功提醒发送结束，该微信公众号为关闭状态", openid);
            return;
        }
        WxMsg wxMsg = new WxMsg();
        wxMsg.setOpenid(openid);
//        String tempId = wxMsgConfigService.getTempId(WxMsgType.UNBIND_WX.getTemplateIdShort());
        // 根据模板code获取模板信息
        WxMsgConfig wxMsgConfig = wxMsgConfigService.getTempIdNew(WxMsgType.UNBIND_WX.getTemplateIdShort());
        if (wxMsgConfig == null){
            return;
        }
        wxMsg.setTemplateId(wxMsgConfig.getTemplateId());
        wxMsg.setFirst("账号解绑成功");
        wxMsg.setKeyword1(accountName);
        wxMsg.setKeyword2("微信手动解绑");
        wxMsg.setKeyword3(DateUtils.dateToString(new Date()));
        // 设置key
        wxMsg.setConfig(JSON.parseObject(wxMsgConfig.getConfig()));
        wxMsg.setRemark("如非本人操作，请及时联系客服查询原因");
//        myConstant.sendTemplateMsg(config, wxMsg);
        myConstant.sendTemplateMsgNew(config, wxMsg);
        LogPortal.info("openid【{}】解绑微信成功提醒发送完成，解绑账号【{}】", openid, accountName);
    }

    public void bindWxFail(String openid, String why, String remark) {
        LogPortal.info("openid【{}】绑定微信失败提醒开始发送，失败信息【why:{},remark:{}】", openid, why, remark);
        WxConfig config = wxConfigService.getConfig();
        if (config.getStatus() == 0) {
            LogPortal.info("openid【{}】绑定微信失败提醒发送结束，该微信公众号为关闭状态", openid);
            return;
        }
        WxMsg wxMsg = new WxMsg();
        wxMsg.setOpenid(openid);
//        String tempId = wxMsgConfigService.getTempId(WxMsgType.BIND_WX_FAIL.getTemplateIdShort());
        // 根据模板code获取模板信息
        WxMsgConfig wxMsgConfig = wxMsgConfigService.getTempIdNew(WxMsgType.BIND_WX_FAIL.getTemplateIdShort());
        if (wxMsgConfig == null){
            return;
        }
        wxMsg.setTemplateId(wxMsgConfig.getTemplateId());
        wxMsg.setFirst("账号绑定失败");
        wxMsg.setKeyword1(why);
        wxMsg.setKeyword2(DateUtils.dateToString(new Date()));
        // 设置key
        wxMsg.setConfig(JSON.parseObject(wxMsgConfig.getConfig()));
        wxMsg.setRemark(remark);
//        myConstant.sendTemplateMsg(config, wxMsg);
        myConstant.sendTemplateMsgNew(config, wxMsg);
        LogPortal.info("openid【{}】绑定微信失败提醒发送完成，失败信息【why:{},remark:{}】", openid, why, remark);
    }

    public void login(Integer merchantId, Integer loginId, String accountName, String loginType,String loginIp) {
        try {
            aybSendMsgUtils.login(merchantId,loginId,accountName,loginType,loginIp);
        } catch (Exception e) {
            LogPortal.error("商户号【{}】爱游宝登录提醒发送失败，发生{}异常",e,merchantId,e.getClass().getName());
            return;
        }
        try {
            WxConfig config = wxConfigService.getConfig();
            if (config.getStatus() == 0) {
                LogPortal.info("商户号【{}】登录提醒发送结束，该微信公众号为关闭状态", merchantId);
                return;
            }
            LogPortal.info("商户号【{}】微信登录提醒开始发送，登录信息【loginId:{},loginAccount:{},loginType:{},loginIp:{}】", merchantId, loginId, accountName, loginType,loginIp);
            List<WxUser> wxUserList = wxUserService.getWxUser(merchantId, loginId);
            if (CollUtil.isNotEmpty(wxUserList)) {
//                String tempId = wxMsgConfigService.getTempId(WxMsgType.LOGIN.getTemplateIdShort());
                // 根据模板code获取模板信息
                WxMsgConfig wxMsgConfig = wxMsgConfigService.getTempIdNew(WxMsgType.LOGIN.getTemplateIdShort());
                if (wxMsgConfig == null){
                    return;
                }
                for (WxUser wxUser : wxUserList) {
                    if (wxUser.getLoginRemindStatus()==1 && wxUser.getSubscribe()==1) {
                        WxMsg wxMsg = new WxMsg();
                        wxMsg.setOpenid(wxUser.getOpenid());
                        wxMsg.setTemplateId(wxMsgConfig.getTemplateId());
                        wxMsg.setFirst("账号登录成功");
                        wxMsg.setKeyword1(accountName);
                        wxMsg.setKeyword2(loginType);
                        wxMsg.setKeyword3(DateUtils.dateToString(new Date()));
                        wxMsg.setKeyword4(loginIp);
                        // 设置key
                        wxMsg.setConfig(JSON.parseObject(wxMsgConfig.getConfig()));
                        wxMsg.setRemark("如非本人登录，请及时修改密码");
//                        myConstant.sendTemplateMsg(config, wxMsg);
                        myConstant.sendTemplateMsgNew(config, wxMsg);
                        LogPortal.info("商户号【{}】登录提醒发送至微信【{}】完成", merchantId, wxUser.getNickname());
                    }
                }
            }else {
                LogPortal.info("商户号【{}】登录提醒发送结束，该商户暂未绑定微信", merchantId);
            }
        } catch (Exception e) {
            LogPortal.error("商户号【{}】登录提醒发送失败，发生{}异常",e,merchantId,e.getClass().getName());
        }
    }

    public void rechargeFail(String first, String remark, String traceId, Order order) {
        try {
            aybSendMsgUtils.rechargeFail(first, remark, traceId, order);
            if (order.getWxNotice()==2){
                return;
            }
            LogPortal.info("订单号【{}】充值失败提醒开始发送", order.getMerchantOrderNo());
            WxConfig config = wxConfigService.getConfig();
            if (config.getStatus() == 0) {
                LogPortal.info("分区id【{}】充值失败提醒发送结束，该微信公众号为关闭状态", order.getMerchantOrderNo());
                return;
            }
            List<WxUser> wxUserList = wxUserService.getWxUser(order.getMerchantId());
            if (CollUtil.isNotEmpty(wxUserList)) {
//                String tempId = wxMsgConfigService.getTempId(WxMsgType.RECHARGE_FAIL.getTemplateIdShort());
                // 根据模板code获取模板信息
                WxMsgConfig wxMsgConfig = wxMsgConfigService.getTempIdNew(WxMsgType.RECHARGE_FAIL.getTemplateIdShort());
                if (wxMsgConfig == null){
                    return;
                }
                String amount = String.format("%.2f", order.getAmount());
                // 精简【】换掉 用：
//                String k2 = "订单号【" + order.getMerchantOrderNo() + "】，充值金额【" + amount + "元】，充值时间【" + DateUtils.dateToString(order.getCreateTime()) + "】";
                String k2 = order.getMerchantOrderNo() + "，充值" + amount + "元";
                // 精简 去掉分区id
//                String k3 = order.getPartitionName() + "【" + order.getPartitionId() + "】";
                String k3 = order.getPartitionName();
                for (WxUser wxUser : wxUserList) {
                    if (wxUser.getWxMsgStatus()==1 && wxUser.getSubscribe()==1) {
                        WxMsg wxMsg = new WxMsg();
                        wxMsg.setOpenid(wxUser.getOpenid());
                        wxMsg.setTemplateId(wxMsgConfig.getTemplateId());
                        wxMsg.setFirst(first);
                        wxMsg.setKeyword1(order.getRechargeNumber());
                        wxMsg.setKeyword2(k2);
                        wxMsg.setKeyword3(k3);
                        wxMsg.setKeyword4(traceId);
                        // 设置key
                        wxMsg.setConfig(JSON.parseObject(wxMsgConfig.getConfig()));
                        wxMsg.setRemark(remark);
                        myConstant.sendTemplateMsgNew(config, wxMsg);
//                        myConstant.sendTemplateMsg(config, wxMsg);
                        LogPortal.info("订单号【{}】充值失败提醒发送至微信【{}】完成", order.getMerchantOrderNo(), wxUser.getNickname());
                    }
                }
            }else {
                LogPortal.info("分区id【{}】充值失败提醒发送结束，该商户暂未绑定微信", order.getMerchantOrderNo());
            }
        } catch (Exception e) {
            LogPortal.info("分区id【{}】充值失败提醒发送失败，发生{}异常",e,order.getMerchantOrderNo(),e.getClass().getName());
        }
    }

    public void rechargeSuccess(Order order) {
        try {
            MerchantAccount merchantAccount =  merchantAccountService.selectOne(order.getMerchantId());
            String accountAmtDesc = "当前账号今日收入金额为：";
            if (merchantAccount != null){
                accountAmtDesc+=merchantAccount.getBalance()+"元";
            }
            aybSendMsgUtils.rechargeSuccess(order,accountAmtDesc);
            LogPortal.info("订单号【{}】充值提醒开始发送", order.getMerchantOrderNo());
            WxConfig config = wxConfigService.getConfig();
            if (config.getStatus() == 0) {
                LogPortal.info("订单号【{}】充值提醒发送结束，该微信公众号为关闭状态", order.getMerchantOrderNo());
                return;
            }
            List<WxUser> wxUserList = wxUserService.getWxUser(order.getMerchantId());
            if (CollUtil.isNotEmpty(wxUserList)) {
//                String tempId = wxMsgConfigService.getTempId(WxMsgType.RECHARGE_SUCCESS.getTemplateIdShort());
                // 根据模板code获取模板信息
                WxMsgConfig wxMsgConfig = wxMsgConfigService.getTempIdNew(WxMsgType.RECHARGE_SUCCESS.getTemplateIdShort());
                if (wxMsgConfig == null){
                    return;
                }
                PartitionDTO partitionDTO = partitionService.getPartitionInfoById(order.getPartitionId());
                String amount = String.format("%.2f", order.getAmount());
                // 精简
//                String k5 = "游戏分区【" + partitionDTO.getPartitionName() + "】，充值时间【" + DateUtils.dateToString(order.getCreateTime()) + "】";
                String k5 = partitionDTO.getPartitionName();
                Merchant merchant = merchantService.find(order.getMerchantId());
//                String first = "您的账户：【" + merchant.getLoginAccount() + "】有一笔新订单";
                String first = "您的账户：" + merchant.getLoginAccount() + "有一笔新订单";

                for (WxUser wxUser : wxUserList) {
                    if (wxUser.getWxRechargeMsgStatus() ==1 && wxUser.getSubscribe()==1) {
                        WxMsg wxMsg = new WxMsg();
                        wxMsg.setOpenid(wxUser.getOpenid());
                        wxMsg.setTemplateId(wxMsgConfig.getTemplateId());
                        wxMsg.setFirst(first);
                        wxMsg.setKeyword1(order.getMerchantOrderNo());
                        wxMsg.setKeyword2(merchant.getLoginAccount() + "【" + merchant.getId() + "】");
                        wxMsg.setKeyword3(order.getRechargeNumber());
                        wxMsg.setKeyword4(amount);
                        wxMsg.setKeyword5(k5);
                        // 设置key
                        wxMsg.setConfig(JSON.parseObject(wxMsgConfig.getConfig()));
                        wxMsg.setRemark(accountAmtDesc);
                        myConstant.sendTemplateMsgNew(config, wxMsg);
//                        myConstant.sendTemplateMsg(config, wxMsg);
                        LogPortal.info("订单号【{}】充值提醒发送至微信【{}】完成", order.getMerchantOrderNo(), wxUser.getNickname());
                    }
                }
            } else {
                LogPortal.info("订单号【{}】充值提醒发送结束，该商户暂未绑定微信", order.getMerchantOrderNo());
            }
        } catch (Exception e) {
            LogPortal.error("订单号【{}】充值提醒发送失败，发生{}异常",e,order.getMerchantOrderNo(),e.getClass().getName());
        }
    }
    public void createPartitionFail(String traceId, Integer merchantId, String first, String partitionId) {
        try {
            aybSendMsgUtils.createPartitionFail(traceId, merchantId, first, partitionId);
            LogPortal.info("分区id【{}】创建分区失败提醒开始发送", partitionId);
            WxConfig config = wxConfigService.getConfig();
            if (config.getStatus() == 0) {
                LogPortal.info("分区id【{}】创建分区失败提醒发送结束，该微信公众号为关闭状态", partitionId);
                return;
            }
            List<WxUser> wxUserList = wxUserService.getWxUser(merchantId);
            if (CollUtil.isNotEmpty(wxUserList)) {
//                String tempId = wxMsgConfigService.getTempId(WxMsgType.CREATE_PARTITION_FAIL.getTemplateIdShort());
                // 根据模板code获取模板信息
                WxMsgConfig wxMsgConfig = wxMsgConfigService.getTempIdNew(WxMsgType.CREATE_PARTITION_FAIL.getTemplateIdShort());
                if (wxMsgConfig == null){
                    return;
                }
                PartitionDTO partitionDTO = partitionService.getPartitionInfoById(partitionId);
                // 精简 去掉分区id
//                String k1 = partitionDTO.getPartitionName() + "【" + partitionId + "】";
                String k1 = partitionDTO.getPartitionName();
                String k2 = partitionDTO.getServerIp() + ":" + partitionDTO.getPortNum();
                for (WxUser wxUser : wxUserList) {
                    if (wxUser.getWxMsgStatus() == 1 && wxUser.getSubscribe()==1) {
                        WxMsg wxMsg = new WxMsg();
                        wxMsg.setOpenid(wxUser.getOpenid());
                        wxMsg.setTemplateId(wxMsgConfig.getTemplateId());
                        wxMsg.setFirst(first);
                        wxMsg.setKeyword1(k1);
                        wxMsg.setKeyword2(k2);
                        wxMsg.setKeyword3(partitionDTO.getInstallPath());
                        wxMsg.setKeyword4(DateUtils.dateToString(new Date()));
                        wxMsg.setKeyword5(traceId);
                        // 设置key
                        wxMsg.setConfig(JSON.parseObject(wxMsgConfig.getConfig()));
                        wxMsg.setRemark("本次异常提醒24小时内只会提醒一次，请及时处理");
//                        myConstant.sendTemplateMsg(config, wxMsg);
                        myConstant.sendTemplateMsgNew(config, wxMsg);
                        LogPortal.info("分区id【{}】创建分区失败提醒发送至微信【{}】完成", partitionId, wxUser.getNickname());
                    }
                }
            }else {
                LogPortal.info("分区id【{}】创建分区失败提醒发送结束，该商户暂未绑定微信", partitionId);
            }
        } catch (Exception e) {
            LogPortal.error("分区id【{}】创建分区失败提醒发送失败，发生{}异常",e,partitionId,e.getClass().getName());
        }
    }
}
